<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Orderlist extends Backend
{

    /**
     * Orderlist模型对象
     * @var \app\admin\model\Orderlist
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orderlist;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();




                $list = $this->model
                    ->with(['user','goods'])
                    ->where($where)
                    ->where('goods.admin_id','eq', $this->auth->id)
                    ->order($sort, $order)
                    ->paginate($limit);




            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname']);
				$row->getRelation('goods')->visible(['name']);


                $buy=Db::name('user')->where('id',$row->buyuser)->find();

                if ($buy){
                    $row->buyuser=$buy['nickname'];
                }else{
                    $row->buyuser='未找到';
                }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 获取 卖家信息
     */
    public function getuser(){


        $keyValue=$this->request->post('keyValue');

        $list = Db::name('user')
            ->alias('a')
            ->join('merch b', 'a.id = b.user_id')
            ->where('b.status', '=', '1')
            ->where('a.admin_id', '=', $this->auth->id)
            ->field('a.id, a.nickname as name')
            ->select();

        foreach ($list as &$key){
            $key['saleuser']=$key['id'];
        }

        // 将 id=$keyValue 的记录放到最前面，其余按 id 降序排列
        usort($list, function($a, $b) use ($keyValue) {
            // 如果 $a 是目标记录，排在前面
            if ($a['id'] == $keyValue) return -1;
            // 如果 $b 是目标记录，排在前面
            if ($b['id'] == $keyValue) return 1;
            // 否则按 id 降序排列
            return $b['id'] <=> $a['id'];
        });


        $result = array("total" => count($list), "rows" => $list);
        return json($result);

    }

    /**
     * 获取 卖家信息
     */
    public function getbuyuser(){

        $keyValue=$this->request->post('keyValue');


            $list = Db::name('user')
                ->alias('a')
                ->field('a.id, a.nickname as name')
                ->select();


        foreach ($list as &$key){

            $key['buyuser']=$key['id'];
        }


        // 将 id=$keyValue 的记录放到最前面，其余按 id 降序排列
        usort($list, function($a, $b) use ($keyValue) {
            // 如果 $a 是目标记录，排在前面
            if ($a['id'] == $keyValue) return -1;
            // 如果 $b 是目标记录，排在前面
            if ($b['id'] == $keyValue) return 1;
            // 否则按 id 降序排列
            return $b['id'] <=> $a['id'];
        });

        $list = array_values($list);


        $result = array("total" => count($list), "rows" => $list);
        return json($result);

    }

    /**
     * 添加信息
     */
    public function add(){


        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }

        $data=$this->request->post();

        $data=$data['row'];


        $gid=$data['goods_id'];
        $goods=Db::name('goods')->where('id',$gid)->find();

        $money=$data['money'];
        $savemoney=$money*$goods['getlv']/100; //服务费
        $getmoney=$money*$goods['fuwu']/100; //收益
        $insert=[];
        $insert['saleuser']=$data['saleuser'];
        $insert['goods_id']=$data['goods_id'];
        $insert['money']=$data['money'];
        $insert['savemoney']=$savemoney;
        $insert['getmoney']=$getmoney;
        $insert['addtime']=time();
        $insert['admin_id']=$this->auth->id;



        Db::name('orderlist')->insertGetId($insert);

        $this->success();



    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;



        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $order=Db::name('orderlist')->where('id',$ids)->find();

            // 添加一个服务订单
            if ($order['status']!=2&&$params['status']==2){

                $fw['user_id']=$order['saleuser'];
                $fw['order']=$order['id'];
                $fw['money']=$order['money'];
                $fw['savemoney']=$order['savemoney'];
                $fw['addtime']=time();
                $fw['admin_id']=$this->auth->id;
                $fw['goods_id']=$order['goods_id'];
                Db::name('fworder')->data($fw)->insert();

            }

            unset($params['admin_id']);
            $result = $row->allowField(true)->save($params);








            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 拆分
     */
    public function split(){


        $ids=$this->request->param('ids');

       if (false === $this->request->isPost()){
           $this->view->assign('ids',$ids);
           return $this->view->fetch();
       }

       $order=Db::name('orderlist')->where('id',$ids)->find();

       if ($order['payimage']){
           $this->error('当前订单已支付，无法拆分');
       }


       $number=$this->request->post('number');
       if ($number<=0){
           $this->error('请输入正确的拆分数量');
       }


       unset($order['id']);

       $order['money']=$order['money']/$number;
       $order['savemoney']=$order['savemoney']/$number;
       $order['getmoney']=$order['getmoney']/$number;
       $order['addtime']=time();
       $order['status']=0;



       for($i=1;$i<=$number;$i++){

           Db::name('orderlist')
               ->data($order)
               ->insert();

       }


       Db::name('orderlist')->where('id',$ids)->delete();

       $this->success();




    }


    /**
      * 导入
     **/
    public function importfile()
    {

        if (false === $this->request->isPost()) {

            $goods=Db::name('goods')->where('admin_id',$this->auth->id)->select();

            $this->view->assign('goodslist',$goods);

            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');

        $file=$params['image'];
        $goodsid=$params['goodsid'];


        $good=Db::name('goods')->where('id',$goodsid)->find();


        $filePath = './'.$file;


        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }



        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        $reader = new Xlsx();


        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];


        //加载文件
        $insert = [];

        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $fields = [];

        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }



        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];

            $buy=Db::name('user')->where('mobile',$values[1])->find();
            $sale=Db::name('user')->where('mobile',$values[0])->find();
            $money=$values[2];

//            var_dump($values);
//            var_dump($insert);
//            var_dump($buy);

            if ($buy&&$sale){



                $savemoney=$money*$good['getlv']/100; //服务费
                $getmoney=$money*$good['fuwu']/100; //收益
                $insert=[];
                $insert['buyuser']=$buy['id'];
                $insert['saleuser']=$sale['id'];
                $insert['goods_id']=$goodsid;
                $insert['money']=$money;
                $insert['savemoney']=$savemoney;
                $insert['getmoney']=$getmoney;
                $insert['addtime']=time();
                $insert['admin_id']=$this->auth->id;



                Db::name('orderlist')->insertGetId($insert);

            }


        }

        $this->success();




    }

    protected function array_sort($array, $key, $sort = 'asc')
    {
        usort($array, function($a, $b) use ($key, $sort) {
            if ($sort == 'asc') {
                return $a[$key] <=> $b[$key];
            } else {
                return $b[$key] <=> $a[$key];
            }
        });
        return $array;
    }


}
